package com.ruoyi.common.sql;

import java.util.Arrays;
import java.util.List;


public class Condition{
    private final String operator;
    private final List<Condition> conditions;
    private final String field;
    private final String comparison;
    private final Object value;
    private final boolean isSubquery;

    private Condition(String operator, List<Condition> conditions) {
        this.operator = operator;
        this.conditions = conditions;
        this.field = null;
        this.comparison = null;
        this.value = null;
        this.isSubquery = false;
    }

    private Condition(String field, String comparison, Object value, boolean isSubquery) {
        this.operator = null;
        this.conditions = null;
        this.field = field;
        this.comparison = comparison;
        this.value = value;
        this.isSubquery = isSubquery;
    }

    public static Condition and(Condition... conditions) {
        return new Condition("AND", Arrays.asList(conditions));
    }

    public static Condition or(Condition... conditions) {
        return new Condition("OR", Arrays.asList(conditions));
    }

    public static Condition eq(String field, Object value) {
        return new Condition(field, "=", value, false);
    }

    public static Condition gt(String field, Object value) {
        return new Condition(field, ">", value, false);
    }

    public static Condition in(String field, SqlBuilder subquery) {
        return new Condition(field, "IN", subquery, true);
    }

    public static Condition notIn(String field, SqlBuilder subquery) {
        return new Condition(field, "NOT IN", subquery, true);
    }

    public void build(StringBuilder sql) {
        if (operator != null) {
            sql.append("(");
            for (int i = 0; i < conditions.size(); i++) {
                if (i > 0) {
                    sql.append(" ").append(operator).append(" ");
                }
                conditions.get(i).build(sql);
            }
            sql.append(")");
        } else {
            sql.append(field).append(" ").append(comparison).append(" ");
            if (isSubquery) {
                sql.append("(").append(((SqlBuilder)value).build()).append(")");
            } else if (value instanceof Number) {
                sql.append(value);
            } else {
                sql.append("'").append(value).append("'");
            }
        }
    }
}
